import type { Recordable, UserInfo } from '@vben/types';

import { ref } from 'vue';
import { useRouter } from 'vue-router';

import { LOGIN_PATH } from '@vben/constants';
import { defineStore } from 'pinia';
import { notification } from '#/adapter/naive';
import { loginApi, logoutApi } from '#/api';
import { $t } from '#/locales';

// 本地存储的 key
const ACCESS_TOKEN_KEY = 'access_token';
const REFRESH_TOKEN_KEY = 'refresh_token';

export const useAuthStore = defineStore('auth', () => {
  const router = useRouter();
  const loginLoading = ref(false);
  const accessToken = ref<string | null>(localStorage.getItem(ACCESS_TOKEN_KEY));
  const refreshToken = ref<string | null>(localStorage.getItem(REFRESH_TOKEN_KEY));

  // 设置 token 并持久化
  function setTokens(access: string | null, refresh: string | null) {
    accessToken.value = access;
    // accessToken.value = 'eyJhbGciOiJSUzI1NiIsImtpZCI6InJzYS1rZXktMSIsInR5cCI6IkpXVCJ9.eyJhdWQiOlsibW9kZWxfbGFrZSJdLCJleHAiOjE3NTMxODIzODAsImlhdCI6MTc1MzE3NTE4MCwiaXNzIjoiaHR0cDovLzE5Mi4xNjguMTkuMjMyOjEwMTAiLCJqdGkiOiIwMTk4MzE2Mi00NTQ0LTc4ODctOWE5MC00MzgwYzU3OTZjMjAiLCJuYmYiOjE3NTMxNzUxODAsInJvbGVzIjpbInN1cGVyX2FkbWluIl0sInNjb3BlIjoib3BlbmlkIHByb2ZpbGUiLCJzdWIiOiIzMjg0ODNhYS1lYmIxLTQ5YzYtOTU1NS0xNGVjYmU5NzQ0YWIifQ.HnFtZkdjLKvumY35cfUeBD18IwWlVITFQWtHYjwosvUdyIlKvXf27JF13ppaZhXACqUgEY36GSLrmU-ygbpv_Tzdgc_EiCyXEbuexeLgmrvSOFR0L_aW_-Ewr2UuJH1GTCJcD6KZu10Mn9uJXXq4Jy21IGLBSyzrxBh7n9tDdJjAg2NOevvhqHHb1j7c-neHxo0FMSNAyPdjttBttm-z9NVUIYPFXR6U3N9fsNUZzX1-KYa3AUYl18PhxufC3s2rJOjwN37aLfz_-ErIS7qkK5uT0uiRCOZCtycvpCDrGSYOtnZrkBGWzr55M1fvlzAhnBaEgCqz7yzFLASN3am73Q';
    refreshToken.value = refresh;

    if (access) {
      localStorage.setItem(ACCESS_TOKEN_KEY, access);
    } else {
      localStorage.removeItem(ACCESS_TOKEN_KEY);
    }

    if (refresh) {
      localStorage.setItem(REFRESH_TOKEN_KEY, refresh);
    } else {
      localStorage.removeItem(REFRESH_TOKEN_KEY);
    }
  }

  // 检查是否有有效的 token
  function hasValidToken(): boolean {
    return !!accessToken.value;
  }

  async function authLogin(params: Recordable<any>, onSuccess?: () => Promise<void> | void) {
    let userInfo: null | UserInfo = null;
    try {
      loginLoading.value = true;
      const res : any = await loginApi(params);

      // 调试：打印完整的响应数据
      console.log('Login API Response:', res);

      // 根据实际的 API 响应结构调整数据提取
      let access_token, refresh_token;

      if (res.result) {
        // 如果响应有 result 字段
        access_token = res.result.access_token || res.result.accessToken;
        refresh_token = res.result.refresh_token || res.result.refreshToken;
      } else {
        // 如果响应直接在根级别
        access_token = res.access_token || res.accessToken;
        refresh_token = res.refresh_token || res.refreshToken;
      }

      console.log('Extracted tokens:', { access_token, refresh_token });

      // 使用新的 setTokens 方法
      setTokens(access_token, refresh_token);

      // 登录成功后直接跳转首页，不做任何权限处理
      onSuccess
        ? await onSuccess?.()
        : await router.push('/');
      notification.success({
        content: $t('authentication.loginSuccess'),
        description: $t('authentication.loginSuccessDesc'),
        duration: 3000,
      });
    } finally {
      loginLoading.value = false;
    }
    return { userInfo };
  }

  async function logout(redirect: boolean = true) {
    try {
      await logoutApi();
    } catch {}

    // 使用新的 setTokens 方法清除 token
    setTokens(null, null);

    if (redirect) {
      await router.replace({ path: LOGIN_PATH });
    }
  }

  async function fetchUserInfo() {
    // 直接返回空对象
    return {};
  }

  function $reset() {
    loginLoading.value = false;
    setTokens(null, null);
  }

  return {
    $reset,
    authLogin,
    fetchUserInfo,
    loginLoading,
    logout,
    accessToken,
    refreshToken,
    setTokens,
    hasValidToken,
  };
});
